﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImageZip
{
    public partial class FormMain : Form
    {
        private int number = 0;
        private int filenumber = 0;
        private int filesize = 300;
        private int fileflag = 90;
        private string result = "";

        public FormMain()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (fBDOpen.ShowDialog() == DialogResult.OK)
            {
                txtSource.Text = fBDOpen.SelectedPath;
                //FindFile(txtSource.Text);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (fBDSave.ShowDialog() == DialogResult.OK)
            {
                txtTarget.Text = fBDSave.SelectedPath;
            }
        }

        private void btnZip_Click(object sender, EventArgs e)
        {
            GetFile(txtSource.Text);
        }


        
        private void bgW_DoWork(object sender, DoWorkEventArgs e)
        {
            //string syncname = e.Argument.ToString();
            HotSync(bgW, e);
        }

        private void bgW_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pBar.Value = e.ProgressPercentage;
            lbprogress.Text = "处理进度:" + Convert.ToString(e.ProgressPercentage) + "/" + number + "条";
            lbnumber.Text = (e.ProgressPercentage * 100 / number).ToString() + "%";
            resultTextBox.Text += result;
            resultTextBox.SelectionStart = lbprogress.Text.Length;
            resultTextBox.ScrollToCaret();
        }

        private void HotSync(BackgroundWorker bgW, DoWorkEventArgs e)
        {
            fileflag =int.Parse(txtFlag.Text);
            filesize =int.Parse(txtSize.Text);
            for (int i = 0; i < filenumber; i++)
            {
                string ret = "";
                if (bgW.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
               string oldfile= dt.Rows[i]["path"].ToString();
               string newfile= dt.Rows[i]["newpath"].ToString();

               Zip.CompressImage(oldfile, newfile, fileflag, filesize);
               ret = i.ToString() + "." + oldfile + " | " + newfile + "\r\n";
               result = ret; 
                bgW.ReportProgress(i + 1, String.Format("{0}%", i + 1));
                Thread.Sleep(100);
            }
        }

        DataTable dt = new DataTable();



        private void SyncStr(string path)
        {
            filenumber = 0;
            GetFileList(path);
        }
        public void GetFileList(string path)
        {
            DirectoryInfo Dir = new DirectoryInfo(path);
            foreach (DirectoryInfo di in Dir.GetDirectories()) // 查找子目录 
            {
                GetFileList(di.FullName);
            }
            foreach (FileInfo fi in Dir.GetFiles())
            {
                string ndir = fi.DirectoryName.Replace(txtSource.Text, txtTarget.Text);
                if (!Directory.Exists(ndir))
                {
                    Directory.CreateDirectory(ndir);
                }
                resultTextBox.Text += ndir + "\\" + fi.Name + "\r\n";
                if (!File.Exists(ndir + "\\" + fi.Name))
                {
                    DataRow row = dt.NewRow();
                    row["path"] = fi.FullName;
                    row["newpath"] = ndir + "\\" + fi.Name;
                    dt.Rows.Add(row);
                    filenumber++;
                }
            } 
        }

        public void GetFile(string path)
        {
            DirectoryInfo Dir = new DirectoryInfo(path);
            foreach (DirectoryInfo di in Dir.GetDirectories()) // 查找子目录 
            {
                GetFile(di.FullName);
            }
            foreach (FileInfo fi in Dir.GetFiles())
            {
                string ndir = fi.DirectoryName.Replace(txtSource.Text, txtTarget.Text);
                if (!Directory.Exists(ndir))
                {
                    Directory.CreateDirectory(ndir);
                }
                if (!File.Exists(ndir + "\\" + fi.Name))
                {
                    Zip.CompressImage(fi.FullName, ndir + "\\" + fi.Name);
                }
            }
        }

        private void bgW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                resultTextBox.Text += "任务取消。" + "\r\n";
            }
            else if (e.Error != null)
            {
                resultTextBox.Text += "出现异常: " + e.Error + "\r\n";
            }
            else
            {
                resultTextBox.Text += "任务完成。 " + "\r\n";
                btnStart.Enabled = true;
                btnCancel.Enabled = false;
            }
            resultTextBox.SelectionStart = lbnumber.Text.Length;
            resultTextBox.ScrollToCaret();
        }

        #region 递归文件
        string FileResult = "";
        public void FindFile(string dir) // 参数为指定的目录 
        {
            // 在指定目录及子目录下查找文件,在listBox1中列出子目录及文件 
            int j = 0;
            DirectoryInfo Dir = new DirectoryInfo(dir);
            try
            {
                foreach (DirectoryInfo d in Dir.GetDirectories()) // 查找子目录 
                {
                    FindFile(Dir + "\\" + d.ToString() + "\\");
                }
                //listView1.BeginUpdate();
                foreach (FileInfo f in Dir.GetFiles()) // 查找文件 
                {
                   // listView1.Items.Add(Dir + f.ToString()); // listBox1中填加文件名 
                    //listView1.Items[j].SubItems.Add(f.Length.ToString());                   
                    //j = j + 1;
                    FileResult += Dir + f.ToString() + "\r\n";
                }
               // listView1.EndUpdate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(" 错误\r\n " + ex.ToString());
            }
        }
        #endregion

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnCancel.Enabled = false;
            bgW.CancelAsync();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnCancel.Enabled = true;
            lbprogress.Text = "处理进度：0/0条";
            lbnumber.Text = "0%";
            pBar.Value = 0;
            string path = txtSource.Text;
            if (!dt.Columns.Contains("path")) { dt.Columns.Add("path", Type.GetType("System.String")); }
            if (!dt.Columns.Contains("newpath")) { dt.Columns.Add("newpath", Type.GetType("System.String")); }
            SyncStr(path);
            number = filenumber;
            result = "";
            pBar.Maximum = number;
            resultTextBox.Text = "任务开始..." + "\r\n";
            bgW.RunWorkerAsync(); 
        }
    }
}
   
